package cn.tedu._05mvcboot04.exception;

import cn.tedu._05mvcboot04.commen.response.JsonResult;
import cn.tedu._05mvcboot04.commen.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理空指针异常
     */
    @ExceptionHandler
    public JsonResult handleNullPointerException(NullPointerException npe){
        //打桩
        log.error(npe.toString());
        //返回数据
        return new JsonResult(StatusCode.NOT_LOGIN, npe.getMessage());
    }

    /**
     * 处理方法参数无效异常
     */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException manve){
        //打桩
        log.error(manve.toString());
        //返回数据
        return new JsonResult(StatusCode.VALIDATED_ERROR, manve.getFieldError().getDefaultMessage());
    }

    /**
     * 处理违反约束异常
     */
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException cve){
        //打桩
        log.error(cve.toString());
        //返回数据
        return new JsonResult(StatusCode.VALIDATED_ERROR,cve.getMessage());
    }

    /**
     * 父类异常处理(兜底)
     */
    @ExceptionHandler
    public JsonResult handleRuntimeException(RuntimeException re){
        //打桩
        log.error(re.toString());
        //返回数据
        return new JsonResult(StatusCode.OPERATION_FAILED,re.getMessage());
    }

    /**
     * 超类异常处理(终极兜底)
     */
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable throwable){
        //打桩
        log.error(throwable.toString());
        //返回数据
        return new JsonResult(StatusCode.OPERATION_FAILED,throwable.getMessage());
    }
}
